# monkey稳定性测试工具主逻辑
import datetime
import re
import subprocess
import threading
import time
import tkinter,os,getpass,tkinter.ttk
import language_chs,public
# 初始化语言对象
languages = language_chs.Language()
languages_all = languages.all_languages()
LOGO_path = public.resource_path(os.path.join('icon', 'android.ico'))

username = getpass.getuser()
# 创建临时文件夹
make_dir = 'C:\\Users\\' + username + '\\Documents\\DA_Tools\\'
make_dir_s = make_dir + 'adb_test_temp\\'
# 记录monkey日志路径
monkey_log_path = make_dir_s + 'monkey_log_path.log'
if not os.path.exists(monkey_log_path):
    with open(monkey_log_path, 'w') as f:
        f.write('')
# 记录cmd结束后的标识
monkey_cmd_end = make_dir_s + 'monkey_cmd_end.log'
# 实时保存设备序列号
devices_log = make_dir_s + 'devices.log'
# monkey种子值保存
monkey_seed_log = make_dir_s + 'monkey_seed.log'
if not os.path.exists(monkey_seed_log):
    with open(monkey_seed_log, 'w') as f:
        f.write('')


class Context:
    """承接上下"""


# 显示页面
def monkey_flame(customize_frame,width_button,adb_test_disable,page_state_list):
    monkey = Monkey()
    monkey_button = tkinter.Button(customize_frame, text=languages_all['monkey_button_name'], width=width_button)
    monkey_button_disable = tkinter.Button(customize_frame, text=languages_all['monkey_button_name'],
                                               width=width_button)
    monkey_button_disable.config(state='disable')
    setattr(Context,"monkey_button",monkey_button)
    setattr(Context,"monkey_button_disable",monkey_button_disable)
    monkey_button.bind('<Button-1>', lambda x: monkey.monkey_form(adb_test_disable,page_state_list))
    monkey_button.place(x=20, y=60)

    if 'monkey' in page_state_list:
        monkey_button.place_forget()
        monkey_button_disable.place(x=20, y=60)
        setattr(Context, "monkey_button", monkey_button)
        setattr(Context, "monkey_button_disable", monkey_button_disable)


def insert_colored_text(text_box,text, fg_color='', bg_color=''):
    # 插入带颜色的文本，其中fg_color是字体颜色，bg_color是字体的背景颜色，text_box是文本框组件，text是要插入的文本
    text_box.tag_configure(fg_color, foreground=fg_color)
    text_box.tag_configure(bg_color, background=bg_color)
    text_box.insert("insert", text, (fg_color, bg_color))


class Monkey(object):
    def monkey_form(self,adb_test_disable,page_state_list):
        self.monkey_root = tkinter.Toplevel()
        self.monkey_root.title(languages_all['monkey_button_name'])
        # screenWidth = self.screen_root.winfo_screenwidth()
        # screenHeight = self.screen_root.winfo_screenheight()
        w = 410
        h = 600
        # x = (screenWidth - w) / 2
        # y = (screenHeight - h) / 2
        self.monkey_root.geometry('%dx%d' % (w, h))
        self.monkey_root.iconbitmap(LOGO_path)
        self.monkey_root.resizable(0, 0)
        # self.screen_root.wm_attributes('-topmost', 1)

        self.adb_test_disable = adb_test_disable
        self.page_state_list = page_state_list

        self.page_state_list.append('monkey')
        self.monkey_startup()

        self.monkey_root.protocol('WM_DELETE_WINDOW',self.close_handle)
        self.main_frame()

        return self.monkey_root

    def monkey_startup(self):
        # 监听当前页面的打开状态
        monkey_exists = self.monkey_root.winfo_exists()
        if monkey_exists == 1:
            try:
                getattr(Context,"monkey_button_disable").place(x=20, y=60)
                getattr(Context, "monkey_button").place_forget()
            except Exception:
                pass
            self.adb_test_disable.place(x=400, y=370)

    def close_handle(self):
        # 监听页面消失
        self.page_state_list.remove('monkey')
        self.monkey_root.destroy()
        try:
            getattr(Context, "monkey_button").place(x=20, y=60)
            getattr(Context, "monkey_button_disable").place_forget()
        except Exception:
            pass
        if not self.page_state_list:
            self.adb_test_disable.place_forget()

    def main_frame(self):
        """主要按钮"""
        # 日志label
        self.log_path_label = tkinter.Label(self.monkey_root,text=languages_all['monkey_log_path_label'],fg='red')
        self.log_path_label.place(x=20,y=20)

        # 日志路径输入框
        self.log_path_str = tkinter.StringVar()
        self.log_path_entry = tkinter.Entry(self.monkey_root, textvariable=self.log_path_str,
                                                   width=40, highlightcolor='red', highlightthickness=5)
        self.log_path_entry.place(x=20, y=50)
        log_path = open(monkey_log_path,'r',encoding='utf-8').read()
        self.log_path_entry.insert(tkinter.END, log_path)
        public.CreateToolTip(self.log_path_label,languages_all['monkey_log_path_label_toast'])

        # 浏览按钮
        self.browse_button = tkinter.Button(self.monkey_root,text=languages_all['browse'])
        self.browse_button_disable = tkinter.Button(self.monkey_root,text=languages_all['browse'])
        self.browse_button_disable.config(state='disable')
        self.browse_button.place(x=330,y=50)
        self.browse_button.bind('<Button-1>',lambda x:self.log_path_bind())

        # 包名label
        self.package_label = tkinter.Label(self.monkey_root, text=languages_all['monkey_package_label'], fg='red')
        self.package_label.place(x=20, y=80)

        # 自动获取当前包名可修改输入框
        self.monkey_package_str = tkinter.StringVar()
        self.monkey_package_entry = tkinter.Entry(self.monkey_root, textvariable=self.monkey_package_str,
                                            width=40, highlightcolor='red', highlightthickness=5)
        self.monkey_package_entry.place(x=20, y=100)
        self.monkey_package_entry.delete(0,tkinter.END)
        self.monkey_package_entry.config(command=self.monkey_found_package())
           
        # 手动加载包名
        self.monkey_manual_button = tkinter.Button(self.monkey_root,text=languages_all['monkey_manual'])
        self.monkey_manual_button_disable = tkinter.Button(self.monkey_root,text=languages_all['monkey_manual'])
        self.monkey_manual_button_disable.config(state='disable')
        self.monkey_manual_button.place(x=320,y=100)
        self.monkey_manual_button.bind('<Button-1>',lambda x:self.monkey_found_package())

        # monkey次数label
        self.monkey_count_label = tkinter.Label(self.monkey_root, text=languages_all['monkey_count'], fg='red')
        self.monkey_count_label.place(x=20, y=130)

        # monkey次数输入框
        self.monkey_count_str = tkinter.StringVar()
        self.monkey_count_entry = tkinter.Entry(self.monkey_root, textvariable=self.monkey_count_str,
                                            width=40, highlightcolor='blue', highlightthickness=5)
        self.monkey_count_entry.place(x=20, y=160)
        self.monkey_count_str.set('10000')

        # 种子值label
        self.seed_label = tkinter.Label(self.monkey_root, text=languages_all['monkey_seed_label'], fg='red')
        self.seed_label.place(x=20, y=190)

        # 种子值启用
        self.seed_on = tkinter.IntVar()
        self.seed_checkbutton = tkinter.Checkbutton(self.monkey_root, text=languages_all['monkey_seed_select'], onvalue=1, offvalue=0,
                                                         variable=self.seed_on)
        self.seed_checkbutton.place(x=225, y=190)

        # 种子值选项
        self.seed_value = tkinter.StringVar()
        self.seed_combobox = tkinter.ttk.Combobox(self.monkey_root, state="normal", width=40,
                                                          textvariable=self.seed_value)
        # state：“正常”，“只读”或“禁用”之一。在“只读”状态下，可能无法直接编辑该值，并且用户只能从下拉列表中选择值。在“正常”状态下，文本字段可直接编辑。在“禁用”状态下，不可能进行交互。
        seed_result = open(monkey_seed_log,'r').read()
        if seed_result == '':
            self.seed_combobox['value'] = (languages_all['monkey_seed_combobox'])
        else:
            self.seed_combobox['value'] = (seed_result)
        self.seed_combobox.current(0)
        self.seed_combobox.place(x=20, y=220)

        # monkey各项参数label
        self.monkey_parameter_label = tkinter.Label(self.monkey_root, text='选择对应参数进行压测：', fg='red')
        self.monkey_parameter_label.place(x=20, y=250)

        # monkey各项参数选项
        self.monkey_parameter_list = []
        self.monkey_parameter_name_list = []
        self.monkey_parameter_value = tkinter.StringVar()
        self.monkey_parameter_combobox = tkinter.ttk.Combobox(self.monkey_root, state="readonly", width=23,textvariable=self.monkey_parameter_value)
        self.monkey_parameter_combobox['value'] = ['--ignore-timeouts 忽略超时','--ignore-crashes 忽略崩溃',
                                                   '--ignore-security-exceptions 忽略许可错误','--ignore-native-crashes 忽略本地崩溃',
                                                   '--monitor-native-crashes 监控本地崩溃']
        self.monkey_parameter_combobox.current(0)
        self.monkey_parameter_combobox.place(x=150,y=250)

        # 显示已选择的参数label
        self.monkey_parameter_select_str = tkinter.StringVar()
        self.monkey_parameter_select_label = tkinter.Label(self.monkey_root, textvariable=self.monkey_parameter_select_str, fg='red')
        self.monkey_parameter_select_label.place(x=20, y=280)
        if not self.monkey_parameter_list:
            self.monkey_parameter_select_str.set('未选择任何参数选项，点击添加按钮添加参数，点击删除按钮删除参数')

        # 点击添加按钮和删除按钮
        self.monkey_parameter_add_button = tkinter.Button(self.monkey_root,text='添加')
        self.monkey_parameter_add_button.place(x=335,y=245)
        self.monkey_parameter_add_button.bind('<Button-1>',lambda x:self.monkey_parameter_add_bind())
        self.monkey_parameter_del_button = tkinter.Button(self.monkey_root,text='删除')
        self.monkey_parameter_del_button.place(x=370,y=245)
        self.monkey_parameter_del_button.bind('<Button-1>',lambda x:self.monkey_parameter_del_bind())

        # 设置各种随机事件的概率
        self.monkey_parameter_probability_label = tkinter.Label(self.monkey_root, text='设置各种随机事件的概率：', fg='red')
        self.monkey_parameter_probability_label.place(x=20, y=310)

        # 各种随机事件的选项
        self.monkey_parameter_probability_list = []
        self.monkey_parameter_probability_name_list = []
        self.monkey_parameter_probability_value = tkinter.StringVar()
        self.monkey_parameter_probability_combobox = tkinter.ttk.Combobox(self.monkey_root, state="readonly", width=30,textvariable=self.monkey_parameter_probability_value)
        self.monkey_parameter_probability_combobox['value'] = ['--pct-touch 触摸事件百分比','--pct-motion 动作事件百分比',
                                                '--pct-pinchzoom 缩放事件的百分比','--pct-trackball 轨迹球事件百分比',
                                                '--pct-rotation 屏幕旋转事件百分比','--pct-nav 导航事件百分比',
                                                '--pct-majornav 主要导航事件百分比','--pct-syskeys 系统按键事件百分比',
                                                '--pct-appswitch 应用启动事件百分比','--pct-flip 键盘事件百分比',
                                                '--pct-anyevent 任何事件百分比']
        self.monkey_parameter_probability_combobox.current(0)
        self.monkey_parameter_probability_combobox.place(x=20,y=340)

        # 随机事件的概率输入框
        self.monkey_parameter_probability_value_2 = tkinter.StringVar()
        self.monkey_parameter_probability_entry = tkinter.Entry(self.monkey_root,width=5,textvariable=self.monkey_parameter_probability_value_2)
        self.monkey_parameter_probability_entry.place(x=255,y=340)
        self.monkey_parameter_probability_value_2.set('0')

        # % label
        self.monkey_parameter_probability_percent_label = tkinter.Label(self.monkey_root,text='%')
        self.monkey_parameter_probability_percent_label.place(x=290,y=340)

        # 点击添加按钮和删除按钮
        self.monkey_parameter_probability_add_button = tkinter.Button(self.monkey_root,text='添加')
        self.monkey_parameter_probability_add_button.place(x=335,y=335)
        self.monkey_parameter_probability_add_button.bind('<Button-1>',lambda x:self.monkey_parameter_probability_add_bind())
        self.monkey_parameter_probability_del_button = tkinter.Button(self.monkey_root,text='删除')
        self.monkey_parameter_probability_del_button.place(x=370,y=335)
        self.monkey_parameter_probability_del_button.bind('<Button-1>',lambda x:self.monkey_parameter_probability_del_bind())

        # 显示已选择的随机事件的文本框
        self.monkey_parameter_probability_select_text = tkinter.Text(self.monkey_root,width=50,height=7)
        self.monkey_parameter_probability_select_text.place(x=20,y=370)
        # 默认添加一个--pct-appswitch事件百分比为0的随机事件
        self.monkey_parameter_probability_list.append('--pct-appswitch 0')
        self.monkey_parameter_probability_name_list.append('应用启动事件百分比 0')
        self.monkey_parameter_probability_select_text.insert('end','已选择的随机事件：\n应用启动事件百分比 0')
        self.monkey_parameter_probability_select_text.config(state=tkinter.DISABLED)  # 禁止编辑

        # 提示label
        self.monkey_parameter_probability_tips_str = tkinter.StringVar()
        self.monkey_parameter_probability_tips_label = tkinter.Label(self.monkey_root, textvariable=self.monkey_parameter_probability_tips_str, fg='red')
        self.monkey_parameter_probability_tips_str.set('默认设置随机事件应用启动事件百分比为0且各事件百分比总和不超过100')
        self.monkey_parameter_probability_tips_label.place(x=15, y=475)

        # 状态
        self.monkey_state_str = tkinter.StringVar()
        self.monkey_state_label = tkinter.Label(self.monkey_root, textvariable=self.monkey_state_str, bg='black',
                                                fg='#ffffff', width=50, height=2)
        self.monkey_state_str.set(languages_all['monkey_state_label'])
        self.monkey_state_label.place(x=20, y=500)

        # 压测按钮
        self.start_monkey = tkinter.Button(self.monkey_root,text=languages_all['monkey_start'],width=20)
        self.start_monkey_disable = tkinter.Button(self.monkey_root,text=languages_all['monkey_start'],width=20)
        self.start_monkey_disable.config(state='disable')
        self.start_monkey.place(x=20,y=550)
        self.start_monkey.bind('<Button-1>',lambda x:self.monkey_start_bind())

        # 停止按钮
        self.stop_monkey = tkinter.Button(self.monkey_root, text=languages_all['monkey_stop'], width=20)
        self.stop_monkey_disable = tkinter.Button(self.monkey_root, text=languages_all['monkey_stop'], width=20)
        self.stop_monkey_disable.config(state='disable')
        self.stop_monkey_disable.place(x=200, y=550)
        self.stop_monkey.bind('<Button-1>',lambda x:self.kill_monkey())

    def get_seed(self):
        # 从日志获取种子值
        log_path = self.log_path_str.get().strip()
        log_result = open(log_path,'r').read()
        seed_result = ''.join(re.findall('seed=(.*?)count=',log_result,re.S)).strip()
        print(f'获取到的种子值:{seed_result}')
        with open(monkey_seed_log,'w') as fp:
            fp.write(seed_result)
        # 展示种子值
        self.seed_combobox['value'] = (seed_result)
        self.seed_combobox.current(0)

    def monkey_parameter_add_bind(self):
        # 添加参数
        def t_monkey_parameter_add():
            parameter_value = self.monkey_parameter_value.get().strip()
            parameter = parameter_value.split(' ')[0]
            if parameter in self.monkey_parameter_list:
                return
            self.monkey_parameter_list.append(parameter)
            parameter_name = parameter_value.split(' ')[1]
            if parameter_name in self.monkey_parameter_name_list:
                return
            self.monkey_parameter_name_list.append(parameter_name)
            print(f'添加的参数为:{parameter}')
            monkey_parameter_name = ' '.join(self.monkey_parameter_name_list)
            self.monkey_parameter_select_str.set('已选择：' + monkey_parameter_name + ' ')

        t_monkey_parameter_add = threading.Thread(target=t_monkey_parameter_add)
        t_monkey_parameter_add.setDaemon(True)
        t_monkey_parameter_add.start()

    def monkey_parameter_del_bind(self):
        def t_monkey_parameter_del():
            if self.monkey_parameter_list:
                self.monkey_parameter_list.pop()
                self.monkey_parameter_name_list.pop()
                monkey_parameter_name = ' '.join(self.monkey_parameter_name_list)
                self.monkey_parameter_select_str.set('已选择：' + monkey_parameter_name + ' ')
                if not self.monkey_parameter_list:
                    self.monkey_parameter_select_str.set('未选择任何参数选项，点击添加按钮添加参数，点击删除按钮删除参数')
            else:
                self.monkey_parameter_select_str.set('未选择任何参数选项，点击添加按钮添加参数，点击删除按钮删除参数')

        t_monkey_parameter_del = threading.Thread(target=t_monkey_parameter_del)
        t_monkey_parameter_del.setDaemon(True)
        t_monkey_parameter_del.start()

    def monkey_parameter_probability_add_bind(self):
        # 添加随机事件
        def t_monkey_parameter_probability_add_bind():
            # 先清空之前的红色提示
            self.monkey_parameter_probability_select_text.config(state='normal')
            monkey_parameter_probability_name = ' '.join(self.monkey_parameter_probability_name_list)
            self.monkey_parameter_probability_select_text.delete('0.0', 'end')
            if monkey_parameter_probability_name != '':
                self.monkey_parameter_probability_select_text.insert(tkinter.END,'已选择的随机事件：\n' + monkey_parameter_probability_name + ' ')
            self.monkey_parameter_probability_select_text.config(state=tkinter.DISABLED)
            # 首先判断百分比是否为数字，如果已提示就不用再判断了
            parameter_probability_percent = self.monkey_parameter_probability_value_2.get().strip()
            if not parameter_probability_percent.isdigit():  # 判断是否为数字
                if '百分比必须为数字' not in self.monkey_parameter_probability_select_text.get('0.0', 'end'):
                    self.monkey_parameter_probability_select_text.config(state='normal')
                    insert_colored_text(self.monkey_parameter_probability_select_text, '\n百分比必须为数字', 'red')
                    self.monkey_parameter_probability_select_text.config(state=tkinter.DISABLED)
            # 判断百分比必须在0和100之间（包括0和100）
            elif int(parameter_probability_percent) < 0 or int(parameter_probability_percent) > 100:
                if '百分比必须在0和100之间（包括0和100）' not in self.monkey_parameter_probability_select_text.get('0.0', 'end'):
                    self.monkey_parameter_probability_select_text.config(state='normal')
                    insert_colored_text(self.monkey_parameter_probability_select_text, '\n百分比必须在0和100之间（包括0和100）', 'red')
                    self.monkey_parameter_probability_select_text.config(state=tkinter.DISABLED)
            else:
                # 计算百分比总和，如果大于100就无法继续添加随机事件
                parameter_probability_percent_list = []
                for i in self.monkey_parameter_probability_list:
                    parameter_probability_percent_list.append(int(i.split(' ')[1]))
                parameter_probability_percent_sum = sum(parameter_probability_percent_list) + int(
                    self.monkey_parameter_probability_value_2.get().strip())
                print(f'百分比总和为:{parameter_probability_percent_sum}')
                if parameter_probability_percent_sum > 100:
                    if '百分比总和不能超过100' not in self.monkey_parameter_probability_select_text.get('0.0', 'end'):
                        self.monkey_parameter_probability_select_text.config(state='normal')
                        insert_colored_text(self.monkey_parameter_probability_select_text, '\n百分比总和不能超过100', 'red')
                        self.monkey_parameter_probability_select_text.config(state=tkinter.DISABLED)
                else:
                    # 添加随机事件
                    parameter_probability_value = self.monkey_parameter_probability_value.get().strip()
                    parameter_probability = parameter_probability_value.split(' ')[0]
                    parameter_probability_name = parameter_probability_value.split(' ')[1]
                    # 获取百分比
                    parameter_probability_percent = self.monkey_parameter_probability_value_2.get().strip()
                    print(f'添加的随机事件为:{parameter_probability_name} {parameter_probability_percent}')
                    if parameter_probability + ' ' + parameter_probability_percent in self.monkey_parameter_probability_list:
                        return
                    self.monkey_parameter_probability_list.append(parameter_probability + ' ' + parameter_probability_percent)
                    if parameter_probability_name + ' ' + parameter_probability_percent in self.monkey_parameter_probability_name_list:
                        return
                    self.monkey_parameter_probability_name_list.append(
                        parameter_probability_name + ' ' + parameter_probability_percent)
                    monkey_parameter_probability_name = ' '.join(self.monkey_parameter_probability_name_list)
                    # 允许编辑
                    self.monkey_parameter_probability_select_text.config(state='normal')
                    # 先清空文本框
                    self.monkey_parameter_probability_select_text.delete(0.0, tkinter.END)
                    # 再插入文本
                    self.monkey_parameter_probability_select_text.insert(tkinter.END, '已选择的随机事件：\n' + monkey_parameter_probability_name + ' ')
                    # 不允许编辑
                    self.monkey_parameter_probability_select_text.config(state='disabled')

        t_monkey_parameter_probability_add_bind = threading.Thread(target=t_monkey_parameter_probability_add_bind)
        t_monkey_parameter_probability_add_bind.setDaemon(True)
        t_monkey_parameter_probability_add_bind.start()

    def monkey_parameter_probability_del_bind(self):
        # 删除随机事件
        def t_monkey_parameter_probability_del_bind():
            try:
                self.monkey_parameter_probability_list.pop()
                self.monkey_parameter_probability_name_list.pop()
            except Exception as e:
                print(e)
            monkey_parameter_probability_name = ' '.join(self.monkey_parameter_probability_name_list)
            # 允许编辑
            self.monkey_parameter_probability_select_text.config(state='normal')
            # 先清空文本框
            self.monkey_parameter_probability_select_text.delete(0.0, tkinter.END)
            # 再插入文本
            if not self.monkey_parameter_probability_list:
                insert_colored_text(self.monkey_parameter_probability_select_text, '未选择任何随机事件，点击添加按钮添加，点击删除按钮删除，随机事件百分比总和不能超过100', 'blue')
            else:
                self.monkey_parameter_probability_select_text.insert(tkinter.END, '已选择的随机事件：\n' + monkey_parameter_probability_name + ' ')
            # 不允许编辑
            self.monkey_parameter_probability_select_text.config(state='disabled')

        t_monkey_parameter_probability_del_bind = threading.Thread(target=t_monkey_parameter_probability_del_bind)
        t_monkey_parameter_probability_del_bind.setDaemon(True)
        t_monkey_parameter_probability_del_bind.start()

    def monkey_found_package(self):
        def t_found_package():
            devices_state = public.device_connect()
            device = open(devices_log, 'r').read()
            if not devices_state:
                self.monkey_package_str.set('')
                self.monkey_package_entry.insert(tkinter.END, languages_all['monkey_devices_null_2'])
            else:
                device_type = public.device_type_android(device)
                if device_type.strip() == 'Android':
                    package_str = public.found_packages(device)
                    self.monkey_package_str.set('')
                    self.monkey_package_entry.insert(tkinter.END,package_str)
                else:
                    self.monkey_package_str.set('')
                    self.monkey_package_entry.insert(tkinter.END,languages_all['monkey_android_null_2'])

        t_found_package = threading.Thread(target=t_found_package)
        t_found_package.setDaemon(True)
        t_found_package.start()

    def log_path_bind(self):
        def t_log_path():
            # 获取日志路径
            self.browse_button.place_forget()
            self.browse_button_disable.place(x=330, y=50)
            log_path = public.browse_bind(True,'txt')
            self.log_path_entry.delete(0,tkinter.END)
            self.log_path_entry.insert(tkinter.END,log_path)
            self.browse_button_disable.place_forget()
            self.browse_button.place(x=330, y=50)

        t_log_path = threading.Thread(target=t_log_path)
        t_log_path.setDaemon(True)
        t_log_path.start()

    def monkey_start_bind(self):
        def t_monkey_start():
            # 开始压测
            self.start_monkey.place_forget()
            self.start_monkey_disable.place(x=20,y=550)
            self.stop_monkey_disable.place_forget()
            self.stop_monkey.place(x=200, y=550)
            self.monkey_state_str.set(languages_all['monkey_start_doing'])
            devices_state = public.device_connect()
            device = open(devices_log, 'r').read()
            if not devices_state:
                self.monkey_state_str.set(languages_all['monkey_devices_null'])
            else:
                device_type = public.device_type_android(device)
                if device_type.strip() == 'Android':
                    package = self.monkey_package_str.get().strip()
                    log_path = self.log_path_str.get().strip()
                    monkey_count = self.monkey_count_str.get().strip()
                    try:
                        if not self.monkey_parameter_list and not self.monkey_parameter_probability_list:
                            monkey_count_str = str(int(monkey_count))  # 判断值是否可以使用整型转换，可以就是数字，否则是非数字类型
                            if self.seed_on.get() == 0:
                                # 2>&1 将错误输出重定向到标准输出，固定的写法，这个也很重要，代表的意思是中间忽略的东西的日志一并输入到指定的文件中。
                                cmd = f'adb -s {device} shell monkey -p {package} -v -v -v {monkey_count_str} ^> {log_path} 2>&1'  # ^>将输出重定向到文件
                                print('最终压测命令：', cmd)
                                # result = public.execute_cmd(cmd)
                                # print('压测结果：\n', result)
                                os.system('start cmd.exe /K ' + cmd)  # /K执行完命令后不关闭cmd窗口
                            else:
                                seed = self.seed_value.get()
                                cmd = f'adb -s {device} shell monkey -s {seed} -p {package} -v -v -v {monkey_count_str} ^> {log_path} 2>&1'
                                print('最终压测命令：', cmd)
                                # result = public.execute_cmd(cmd)
                                # print('压测结果：\n', result)
                                os.system('start cmd.exe /K ' + cmd)
                        else:
                            monkey_parameter = ' '.join(self.monkey_parameter_list)
                            monkey_parameter_probability = ' '.join(self.monkey_parameter_probability_list)
                            if self.seed_on.get() == 0:
                                cmd = f'adb -s {device} shell monkey -p {package} {monkey_parameter} {monkey_parameter_probability} -v -v -v  {monkey_count} ^> {log_path} 2>&1'
                                print('最终压测命令：', cmd)
                                # result = public.execute_cmd(cmd)
                                # print('压测结果：\n', result)
                                os.system('start cmd.exe /K ' + cmd)
                            else:
                                seed = self.seed_value.get()
                                cmd = f'adb -s {device} shell monkey -s {seed} -p {package} {monkey_parameter} {monkey_parameter_probability} -v -v -v  {monkey_count} ^> {log_path} 2>&1'
                                print('最终压测命令：', cmd)
                                # result = public.execute_cmd(cmd)
                                # print('压测结果：\n', result)
                                os.system('start cmd.exe /K ' + cmd)

                        # if result.strip() == '':  # 压测无异常
                        #     self.monkey_state_str.set('Monkey压测无异常！！！')
                        # else:  # 记录崩溃报错信息
                        #     print('压测异常，详细请看日志！！！')
                        #     # 按照当前时间记录结果到桌面上
                        #     desktop_path = os.path.join(os.path.expanduser('~'), 'Desktop')
                        #     time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
                        #     monkey_log_path_2 = os.path.join(desktop_path, f'monkey_log_{time}.txt')
                        #     with open(monkey_log_path_2,'w',encoding='utf-8') as fp:
                        #         fp.write(result)
                        #     self.monkey_state_str.set('Monkey压测异常\n详细请看日志！！！')

                        # 不断检测文件大小，当文件大小不再变化时，说明压测结束
                        time.sleep(2)
                        setattr(Context, "monkey_my_stop", False)  # 重置压测中断标志
                        while True:
                            time.sleep(1)
                            if getattr(Context, "monkey_my_stop"):
                                print('压测中断！！！')
                                setattr(Context,'monkey_my_stop_2',True)
                                break
                            if os.path.exists(log_path):
                                log_size = os.path.getsize(log_path)
                                time.sleep(1)
                                log_size_2 = os.path.getsize(log_path)
                                if log_size == log_size_2:
                                    print('压测结束！！！')
                                    break
                                else:
                                    continue
                            else:
                                break

                        # 记录种子值
                        self.get_seed()
                        # 分析压测结果
                        log_result = open(log_path, 'r').read()
                        if 'Monkey finished' in log_result:
                            # 压测成功才会保存路径
                            with open(monkey_log_path,'w') as fp:
                                fp.write(log_path)
                            self.monkey_state_str.set(languages_all['monkey_start_success'])
                        elif 'No activities found to run' in log_result:
                            self.monkey_state_str.set(languages_all['monkey_result_by_package_fail'])
                        elif 'Monkey aborted due to error' in log_result:
                            self.monkey_state_str.set('Monkey压测失败(注意cmd窗口的堆栈backtrace信息)\n详细请看日志！！！')
                        else:
                            if getattr(Context,"monkey_my_stop"):
                                pass
                            else:
                                self.monkey_state_str.set(languages_all['monkey_start_fail'])
                    except ValueError:
                        self.monkey_state_str.set(languages_all['monkey_count_error'])
                    except Exception:
                        self.monkey_state_str.set(languages_all['monkey_path_error'])
                else:
                    self.monkey_state_str.set(languages_all['monkey_android_null'])

            self.start_monkey_disable.place_forget()
            self.start_monkey.place(x=20,y=550)
            self.stop_monkey.place_forget()
            self.stop_monkey_disable.place(x=200, y=550)

        t_monkey_start = threading.Thread(target=t_monkey_start)
        t_monkey_start.setDaemon(True)
        t_monkey_start.start()

    def kill_monkey(self):
        def t_kill_monkey():
            """强制结束monkey服务"""
            self.start_monkey.place_forget()
            self.stop_monkey_disable.place(x=200, y=350)
            self.monkey_state_str.set('正在中断monkey压测，请稍等...')
            device = open(devices_log, 'r').read()
            monkey_process = public.execute_cmd('adb -s ' + device + ' shell ps -A | findstr monkey')
            print(monkey_process)
            try:
                monkey_process_finally = [i for i in monkey_process.split(' ') if i != ''][1]
                public.execute_cmd('adb -s ' + device + ' shell kill ' + monkey_process_finally)
            except Exception:
                pass
            setattr(Context,"monkey_my_stop",True)
            setattr(Context, 'monkey_my_stop_2', False)
            while True:
                if getattr(Context,'monkey_my_stop_2'):
                    break
            self.monkey_state_str.set(languages_all['monkey_stop_doing'])

        t_kill_monkey = threading.Thread(target=t_kill_monkey)
        t_kill_monkey.setDaemon(True)
        t_kill_monkey.start()

